package org.clever.arkdemo.database;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class SqlImport {

    public static void importSqlFile(String sqlText, String database, Connection connection) throws SQLException {


        if (database == null || database.isEmpty()) {
            throw new RuntimeException("数据库名称不能为空");
        }
        if (connection == null) {
            throw new RuntimeException("数据库连接不能为空");
        }
        if (sqlText == null || sqlText.isEmpty()) {
            throw new RuntimeException("sql文本不能为空");
        }

        String create = "CREATE DATABASE IF NOT EXISTS `" + database + "`";
        Statement statement = connection.createStatement();
        statement.execute(create);
        statement.execute("USE `" + database + "`");


        List<String> strings = splitSqlScript(sqlText);

        for (String string : strings) {
            string = string.trim();
            if (!string.isEmpty()) {
                try {
                    statement.execute(string);
                } catch (Exception e) {
                    System.out.println(string+"; error");
                    throw  e;
                }
            }

        }




    }



    public static List<String> splitSqlScript(String sqlScript) {
        List<String> statements = new ArrayList<>();
        StringBuilder currentStatement = new StringBuilder();
        boolean endOfStatement = false;
        for (int i = 0; i < sqlScript.length(); i++) {
            char c = sqlScript.charAt(i);
            currentStatement.append(c);
            if (c == ';') {
                endOfStatement = true;
            } else if (c == ' ' || c == '\t' || c == '\r') {

            } else if (c == '\n' && endOfStatement) {
                String string = currentStatement.toString().trim();
                if (!string.isEmpty()) {
                    statements.add(string);
                    currentStatement.setLength(0);
                    endOfStatement = false;
                }
            } else {
                endOfStatement = false;
            }
        }

        // 如果最后还有剩余的语句
        if (currentStatement.length() > 0) {
            statements.add(currentStatement.toString().trim());
        }

        return statements;
    }

}
